/**
 *
 */
package com.rf.richfitwheel.admin.sys.controller;

import com.rf.richfitwheel.admin.annotation.ModifyAnnotaionFactory;
import com.rf.richfitwheel.admin.annotation.UserOperateLog;
import com.rf.richfitwheel.admin.sys.model.Role;
import com.rf.richfitwheel.admin.sys.model.RoleMenu;
import com.rf.richfitwheel.admin.sys.model.UserRole;
import com.rf.richfitwheel.admin.sys.service.SysMenuService;
import com.rf.richfitwheel.admin.sys.service.SysRoleService;
import com.rf.richfitwheel.admin.sys.service.SysUserRoleService;
import com.rf.richfitwheel.admin.sys.vo.UserVO;
import com.rf.richfitwheel.admin.utils.UserUtil;
import com.rf.richfitwheel.common.contants.CommonServiceError;
import com.rf.richfitwheel.common.exception.BusinessException;
import com.rf.richfitwheel.common.utils.PageUtils;
import com.rf.richfitwheel.common.utils.R;
import com.rf.richfitwheel.common.utils.StringUtils;
import com.rf.richfitwheel.common.utils.TreeUtils;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色管理
 * @author hushouquan
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController {

    private static Logger log = LoggerFactory.getLogger(SysRoleController.class);

    @Resource(name = "sysRoleService")
    private SysRoleService sysRoleService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    /**
     * 角色分页查询
     * @param params
     * @return
     */
    @GetMapping("/list")
//	@RequiresPermissions("sys:role:list")
    public R list(@RequestParam Map<String, Object> params) {
        //如果不是超级管理员，则只查询自己租户的角色列表
        UserVO userVO = UserUtil.getUser();
        PageUtils page = sysRoleService.queryPage(params, userVO);

        return R.ok().put("page", page);
    }

    /**
     * 角色分页查询
     * @param params
     * @return
     */
    @GetMapping("/getRoleByParams")
    public R getRoleByParams(@RequestParam Map<String, Object> params) {
        //如果不是超级管理员，则只查询自己租户的角色列表
        UserVO user = UserUtil.getUser();
        List<Role> list = sysRoleService.getRoleByParams(params);
        return R.ok().put("roleList", list);
    }

    /**
     * 根据角色id加载资源树权限
     * @param id 角色id
     * @return
     * @throws Exception
     */
    @GetMapping("/getRoleResTree/{id}")
    public R getRoleResTree(@PathVariable("id") String id) throws Exception {
        List<String> terminals = new ArrayList<String>();
        UserVO userVO = UserUtil.getUser();
        List<TreeUtils> list = sysMenuService.gerResTreeByTerminal(terminals, userVO);
        List<RoleMenu> asingRes = new ArrayList<RoleMenu>();
        asingRes = sysRoleService.getResTreeByRoleId(id);
        return R.ok().put("tree", list).put("asingRes", asingRes);
    }

    /**
     * 根据角色ID和所属模块加载资源树权限
     * @param id
     * @param moduleType
     * @return
     * @throws Exception
     */
    @GetMapping("/getRoleResTree/{id}/{moduleType}")
    public R getRoleResTreeByModule(@PathVariable("id") String id, @PathVariable("moduleType") String moduleType) throws Exception {
        List<String> terminals = new ArrayList<String>();
        UserVO userVO = UserUtil.getUser();
        List<TreeUtils> list = sysMenuService.gerResTreeByModuleType(userVO, moduleType);
        List<RoleMenu> asingRes = new ArrayList<RoleMenu>();
        asingRes = sysRoleService.getResTreeByRoleIdAndModuleType(id, moduleType);
        return R.ok().put("tree", list).put("asingRes", asingRes);
    }

    /**
     * 根据id查询角色信息
     * @param roleId
     * @return
     */
    @GetMapping("/info/{roleId}")
//	@RequiresPermissions("sys:role:info")
    public R info(@PathVariable("roleId") String roleId) {
        Role role = sysRoleService.selectById(roleId);
        return R.ok().put("role", role);
    }

    /**
     * 新增角色信息
     * @param role
     * @return
     */
    @PostMapping("/save")
//	@RequiresPermissions("sys:role:save")
    @UserOperateLog(module = "系统功能", methods = "save", description = "新增角色", functionNo = "101044")
    public R save(@RequestBody Role role) {
        try {
            boolean checkRoleName = sysRoleService.checkRoleName(role.getModuleType(), role.getRoleName());
            if (checkRoleName) {
                return R.error().put("msg", "岗位名称在当前机构下模块已经存在");
            }
            UserVO userVO = UserUtil.getUser();
            sysRoleService.save(role, userVO);
            ModifyAnnotaionFactory.newInstance().ModifyAnnotation(getClass(), UserOperateLog.class, "save", "bussid", role.getId(), role.getClass());
            return R.ok();
        } catch (BusinessException e){
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error(CommonServiceError.SERVICE_SAVE.getMsg() + "角色信息" + CommonServiceError.SERVICE_FAILURE.getMsg(), e);
            return R.error(CommonServiceError.SERVICE_SAVE.getMsg() + "角色信息" + CommonServiceError.SERVICE_FAILURE.getMsg());
        }
    }

    /**
     * 修改角色信息
     * @param role
     * @return
     */
    @PostMapping("/update")
    @UserOperateLog(module = "系统功能", methods = "update", description = "修改角色", functionNo = "101045")
//	@RequiresPermissions("sys:role:update")
    public R update(@RequestBody Role role) {

        try {
//			if (role.getResId() == null || role.getResId().length == 0){
//				return R.error("菜单权限不能为空！");
//			}
            UserVO userVO = UserUtil.getUser();
            if ("1".equals(role.getId())) {
                Map<String, Object> map = new HashMap<>();
                //超级管理员角色只能由超级管理员维护
                List<UserRole> listUser = sysUserRoleService.getListByUserId(userVO.getId());
                for(UserRole ur : listUser){
                    map.put(ur.getRoleId(), ur);
                }
                if(!map.containsKey("1")){
                    return R.error("只有超级管理员可以操作这条数据！");
                }
            }
            sysRoleService.update(role, userVO);
            ModifyAnnotaionFactory.newInstance().ModifyAnnotation(getClass(), UserOperateLog.class, "update", "bussid", role.getId(), role.getClass());
            return R.ok();
        } catch (BusinessException e){
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error(CommonServiceError.SERVICE_MODIFY.getMsg() + "角色信息" + CommonServiceError.SERVICE_FAILURE.getMsg(), e);
            return R.error(CommonServiceError.SERVICE_MODIFY.getMsg() + "角色信息" + CommonServiceError.SERVICE_FAILURE.getMsg());
        }
    }

    /**
     * 删除角色信息
     * @param roleIds
     * @return
     */
    @PostMapping("/delete")
//	@RequiresPermissions("sys:role:delete")
    @UserOperateLog(module = "系统功能", methods = "delete", description = "删除角色", functionNo = "101046")
    public R delete(@RequestBody String[] roleIds) {
        try {
            for (String roleId : roleIds) {
                if ("1".equals(roleId)) {
                    return R.error("内置角色请勿删除！");
                }
            }
            sysRoleService.deleteBatch(roleIds);
            ModifyAnnotaionFactory.newInstance().ModifyAnnotation(getClass(), UserOperateLog.class, "delete", "bussid", roleIds.toString(), roleIds.getClass());
            return R.ok();
        } catch (Exception e) {
            log.error(CommonServiceError.SERVICE_MODIFY.getMsg() + "角色信息" + CommonServiceError.SERVICE_FAILURE.getMsg(), e);
            return R.error(CommonServiceError.SERVICE_MODIFY.getMsg() + "角色信息" + CommonServiceError.SERVICE_FAILURE.getMsg());
        }
    }

    /**
     * 设置角色资源
     * @param role
     * @return
     */
    @PostMapping("/setRoleMenu")
    @UserOperateLog(module = "系统功能", methods = "setRoleMenu", description = "设置资源权限", functionNo = "101047")
    public R setRoleMenu(@RequestBody Role role) {
        try {
            UserVO userVO = UserUtil.getUser();
            sysRoleService.setRoleMenu(role, userVO);
            ModifyAnnotaionFactory.newInstance().ModifyAnnotation(getClass(), UserOperateLog.class, "setRoleMenu", "bussid", role.getId().toString(), role.getClass());
            return R.ok();
        } catch (Exception e) {
            log.error("设置资源权限" + CommonServiceError.SERVICE_FAILURE.getMsg(), e);
            return R.error("设置资源权限" + CommonServiceError.SERVICE_FAILURE.getMsg());
        }
    }

    /**
     * 获取角色下用户列表
     * @param params
     * @return
     */
    @GetMapping("/roleUserList")
    public R roleUserList(@RequestParam Map<String, Object> params) {
        PageUtils page = sysRoleService.queryUserRoleList(params);
        return R.ok().put("page", page);
    }

    /**
     * 获取有效用户，不包含已添加的用户，只能选择当前角色租户下的用户
     * @param params
     * @return
     */
    @GetMapping("/roleUserNoChooseList")
    public R roleUserNoChooseList(@RequestParam Map<String, Object> params) {
        UserVO userVO = UserUtil.getUser();
        PageUtils page = sysRoleService.queryUserRoleNoChooseList(params, userVO);
        return R.ok().put("page", page);
    }

    /**
     * 给角色添加用户
     * @param params
     * @return
     */
    @PostMapping("/setSysRoleUser")
    @UserOperateLog(module = "系统功能", methods = "setSysRoleUser", description = "设置用户角色", functionNo = "101048")
    public R setSysRoleUser(@RequestBody Map<String, Object> params) {
        try {
            String userId = params.get("userId") == null ? null : params.get("userId").toString();
            if (StringUtils.isBlank(userId)) {
                throw new BusinessException("用户id不能为空！");
            }
            String roleId = params.get("roleId") == null ? null : params.get("roleId").toString();
            if (StringUtils.isBlank(roleId)) {
                throw new BusinessException("角色id不能为空！");
            }
            UserVO userVO = UserUtil.getUser();
            sysRoleService.setSysRoleUser(userId, roleId, userVO);
            ModifyAnnotaionFactory.newInstance().ModifyAnnotation(getClass(), UserOperateLog.class, "setSysRoleUser", "bussid", params.toString(), Map.class);
            return R.ok();
        } catch (BusinessException e) {
            log.error("设置用户角色" + CommonServiceError.SERVICE_FAILURE.getMsg() + ":" + e.getMessage(), e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error("设置用户角色" + CommonServiceError.SERVICE_FAILURE.getMsg(), e);
            return R.error("设置用户角色" + CommonServiceError.SERVICE_FAILURE.getMsg());
        }
    }


    @GetMapping("/getRoleList")
//	@RequiresPermissions("sys:role:list")
    public R getRoleList(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        String moduleType = request.getHeader("moduleType") == null ? request.getHeader("Moduletype") : request.getHeader("moduleType"); //从请求头获取模块类型，如果有值就查对应模块菜单
        params.put("moduleType", moduleType);
        //如果不是超级管理员，则只查询自己租户的角色列表
        UserVO user = UserUtil.getUser();
        List<Role> roles = sysRoleService.getRoleList(params, user);

        return R.ok().put("roles", roles);
    }

    /**
     * 根据用户ID获取所拥有的角色信息
     * @param userId
     * @return
     */

    @GetMapping("/getRoleDataByUserId/{userId}")
    public R getRoleDataByUserId(@PathVariable("userId") String userId) {
        JSONArray jsonArray = sysRoleService.getRoleDataByUserId(userId);
        return R.ok().put("roleDataByOrg", jsonArray);
    }


    /**
     * 根据模块类型获取所拥有的角色信息
     * @param moduleType
     * @return
     */

    @GetMapping("/getRoleDataByModuleType/{moduleType}")
    public R getRoleDataByModuleType(@PathVariable("moduleType") String moduleType) {
        Map<String, Object> params = new HashMap<>();
        params.put("moduleType", moduleType);
        List<Role> list = sysRoleService.getRoleByParams(params);
        return R.ok().put("roleDataByModule", list);
    }

}
